package service

import (
	"context"
	"fmt"
	"time"

	"go.uber.org/zap"

	"torler.com/qingyue/apps/backend/internal/app/core"
	"torler.com/qingyue/apps/backend/internal/store"
	v1 "torler.com/qingyue/apps/backend/internal/transport/http/v1"
	"torler.com/qingyue/common/types"
	"torler.com/qingyue/pkg/email"
	"torler.com/qingyue/pkg/logger"
	"torler.com/qingyue/pkg/random"
)

type BasicService struct {
	Container *core.Container
	Store     *store.StoreManager
}

func NewBasicService(Container *core.Container, sotre *store.StoreManager) *BasicService {
	return &BasicService{

		Container: Container,
		Store:     sotre,
	}
}

// SendValidCode
func (service *BasicService) SendValidCode(ctx context.Context, req *v1.ValidCodeReq) (bool, error) {
	logger := logger.Default()
	code, err := service.Store.GetValidCode(ctx, req.CodeType, req.Target)
	if err != nil {
		return false, v1.ErrValidCodeSendFailed
	}
	if code != "" {
		logger.Info("验证码已经发送过了", zap.String("code", code))
		return false, v1.ErrValidCodeAlreadySend
	}
	code = random.GenerateNumericCode(4)

	logger = logger.With(zap.String("code", code))
	//通过过邮箱发送验证码
	if req.CodeType == types.ValidCodeTypeEmail {
		mailConfig := service.Container.Config.Mail
		mailInfo := email.MailInfo{
			To:      []string{req.Target},
			Subject: fmt.Sprintf("[%s]您申请的验证码", mailConfig.TitlePrefix),
			Body:    fmt.Sprintf("您的验证码为:%s，有效期%d分钟", code, mailConfig.Expire),
		}
		err := email.SendEmail(mailConfig, mailInfo)
		if err != nil {
			logger.Error("通过邮件发送验证码失败", zap.Error(err))
			return false, v1.ErrValidCodeSendFailed
		}
		service.Store.SaveValidCode(ctx, req.CodeType, req.Target, code, time.Duration(mailConfig.Expire)*time.Minute)
		logger.Info("发验证码成功")

		return true, nil
	}

	return false, nil
}
